#!/usr/bin/env python
import commands, subprocess, re, time, sys, csv
from datetime import datetime
from os.path import exists

number_re = "+([0-9]+\.[01-9]+|[0-9]+)"

def drop_caches():
    number_re = " +([0-9]+\.[0-9]+|[0-9]+)"
    before = commands.getoutput('cat /proc/meminfo')
    mem_total = re.findall("MemTotal:"+number_re, before)[0]
    before_cached = re.findall("Cached:"+number_re, before)[0]
    before_free = re.findall("MemFree:"+number_re, before)[0]
    commands.getoutput('echo 3 | sudo tee /proc/sys/vm/drop_caches')
    after = commands.getoutput('cat /proc/meminfo')
    after_cached = re.findall("Cached:"+number_re, after)[0]
    after_free = re.findall("MemFree:"+number_re, after)[0]
    print 'drop caches.'
    print 'MemTotal:', mem_total,'kB'
    print 'before MemFree:', before_free,'kB','before Cached:', before_cached,'kB'
    print 'after MemFree:', after_free,'kB','after Cached:', after_cached,'kB'

def get_synchronization_overhead(log):
    try:
        #return re.findall('Elasped time : '+number_re, log)[0]
        val = re.findall('overhead = '+number_re, log)[0]
        return val
    except:
        return '-'

for version in ['PthreadMutexLock']:
#for version in ['TMCSpinLock']:
#for version in ['PthreadBarrier']:
#for version in ['TmcSpinBarrier']:
#for version in ['SpinningCentralBarrier']:
#for version in ['SpinningDisseminationBarrier']:
#for version in ['FetchAndAdd']:
#for version in ['CompareAndExchangeVal']:
#for version in ['CompareAndExchangeBool']:
  log = open('./log/'+version+'.csv', 'w+')
  for numOperations in ['10000']:
    for delay in ['100']:
      log.write(version)
      log.write('\n')
      log.write('2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36'+'\n')
      #for numThreads in ['2','4','6','8','10','12','14','16','18','20','22','24','26','28','30','32','34','36']:
      for numThreads in ['2','4','6','8','10','12','14','16','18','20','22','24','26','28','30','32','34','36','38','40','42','44','46','48','50','52','54','56','58','60','62','64','66','68','70','72','74','76','78','80']:
        cmd = './test_bench '+numThreads
        drop_caches()
        output = commands.getoutput(cmd)
        overhead = get_synchronization_overhead(output)
        log.write(overhead+',')
      log.write('\n')
  log.close()

